package com.dc.ai.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.dc.ai.entity.po.LoginResult;
import com.dc.ai.security.constant.JwtClaimConstants;
import com.dc.ai.security.constant.SecurityConstants;
import com.dc.ai.security.utils.JwtUtils;
import com.dc.ai.service.AuthService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class AuthServiceImpl implements AuthService {

    private final AuthenticationManager authenticationManager;
    private final RedisTemplate<String,Object> redisTemplate;


    @Override
    public LoginResult login(String username, String password) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(username.trim(), password);
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        String accessToken = JwtUtils.generateToken(authentication,redisTemplate);
        return LoginResult.builder()
                .tokenType("Bearer")
                .username(username)
                .accessToken(accessToken)
                .build();
    }

    @Override
    public void logout() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);

        if (StrUtil.isNotBlank(token)) {

            Map<String, Object> claims = JwtUtils.parseToken(token);
            String userId = Convert.toStr(claims.get(JwtClaimConstants.USER_ID));
            redisTemplate.delete(SecurityConstants.USER_TOKEN_PREFIX+ userId);
        }
        SecurityContextHolder.clearContext();
    }
}